package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class WechatUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProp;

    /**
     * 获取token，获取userid
     * 放入ThreadLocal中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取请求路径
        String path = request.getRequestURI();
        log.info("path={}",path);
//        判断是否登录，就放行
        if ("/customer/user/login".equals(path)){
           return true;
        }
//        从头中 key authorization 获取token
        String token = request.getHeader("authorization");
//        判断token是否有值
        if (StringUtils.isBlank(token)){
            log.error("token为空");
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
//        解析token,获取userId
        Map<String,Object> claims =  JwtUtil.parseJWT(jwtProp.getBase64EncodedSecretKey(),token);
        log.info("claims={}",claims);
//        把userId放入ThreadLocal中
        UserThreadLocal.set(Long.valueOf(claims.get(Constants.JWT_USERID).toString()));
        UserThreadLocal.setSubject(claims.get(Constants.JWT_USERNAME).toString());
        return true;
    }

    /**
     * 移除ThreadLocal中数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        UserThreadLocal.removeSubject();
    }
}
